package mk.com.ldm.corepoint.implementation.client.lib.validation;

import java.util.HashMap;

import mk.com.ldm.corepoint.implementation.client.CoreService;
import mk.com.ldm.corepoint.implementation.client.CoreServiceAsync;
import mk.com.ldm.corepoint.implementation.client.lib.generators.BaseWidget;
import mk.com.ldm.corepoint.implementation.shared.FormRow;
import mk.com.ldm.corepoint.implementation.shared.TemporaryStorage;

import org.gwt.mosaic.ui.client.InfoPanel;
import org.gwt.mosaic.ui.client.MessageBox;
import org.gwt.mosaic.ui.client.MessageBox.ConfirmationCallback;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.datepicker.client.DateBox;

public class Validator {

	private static Validator validator;
	CoreServiceAsync rpcService = GWT.create(CoreService.class);
	HashMap<String,String> regexList = new HashMap<String,String>();
	private HashMap<String, Boolean> errorFlag = new HashMap<String, Boolean> ();
	
	
	protected Validator() {
		regexList.put("T", "([A-Za-z0-9-]+)");
		regexList.put("N", "([0-9]*)");
		regexList.put("F", "([0-9]*)\\.?([0-9]*)");
		regexList.put("E", "/^\\s*[a-z\\d_]{1,255}@[a-z\\d\\-]{1,255}\\.[a-z]{2,6}\\s*$/");
		regexList.put("NE", ".+");
	}

	public Boolean addErrorFlag(String itemName, Boolean valid) {
		return errorFlag.put(itemName, valid);
	}

	
	public static Validator getInstance() {
		if (validator == null)
			validator = new Validator();
		return validator;
	}

	public void validateListView(FormRow config, final TextBox textbox, final BaseWidget widget){ 
//		String objectName = config.getTag().split(",")[0];
//		String listName = config.getTag().split(",")[2];
		String[] token = History.getToken().split("/");
		String name = ""; 
		if(token.length > 2) name = token[2]; 
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("username", Cookies.getCookie("username"));
		params.put("objectName", config.getTag().split(",")[0]);
		params.put("name", name);
		params.put("listID", config.getTag().split(",")[2]);
		params.put("listName", config.getTag().split(",")[1]);
		rpcService.validateListView(params, textbox.getValue(), new AsyncCallback<String> (){

			@Override
			public void onFailure(Throwable caught) {
				InfoPanel.show("Server", "Failed to communicate with the server.");
			}

			@Override
			public void onSuccess(String result) {
				if(result.isEmpty()){
					textbox.addStyleName("ui-Invalid");
					widget.setValid(false);
				} else {
					textbox.removeStyleName("ui-Invalid");
					textbox.setTitle(result);
					widget.setValid(true);
				}
				
			
				textbox.setTitle(result);
			}
			
		});
		
	}
	
	public void validateInput(BaseWidget widget, TextBox textbox, String type){
		Boolean flag;
		
		if(!regexList.get(type).isEmpty() && !textbox.getValue().matches(regexList.get(type))){
				textbox.addStyleName("ui-Invalid");
				widget.setValid(false);
				flag = true;
			} else {
				textbox.removeStyleName("ui-Invalid");
				widget.setValid(true);
				flag = false;
		}

		if(errorFlag.get(widget.getName()) != null){
			errorFlag.remove(widget.getName());
			errorFlag.put(widget.getName(), flag);
		} else {
			errorFlag.put(widget.getName(), flag);
		}
		
	}
	
	public void validateDateBoxInput(){
	}
	
	public Boolean checkForErrors(){
	
//		Set<String> names = errorFlag.keySet();
//		Iterator<String> counter = names.iterator();
//		
//		while(counter.hasNext()){
//			String key = counter.next();
//			if(errorFlag.get(key) == false){
//				MessageBox.error("Invalid input", "There are errors in the input fields, caused by invalid input types. Fix these errors (fields marked with a red background) before saving.");
//				return true; 
//			}
//		}
		for(final BaseWidget widget:TemporaryStorage.getInstance().getReference()){
			if(widget != null && widget.getType() == 7){
				String styles = widget.getStyleName();
				int indexOfInvalid = styles.indexOf("dateBoxFormatError");
				if(indexOfInvalid != -1){
					widget.setValid(false);
				} else {
					widget.setValid(true);
				}
			}
			if(widget != null && widget.getValid() == false){
				MessageBox.confirm("Invalid input", "There are errors in the input fields, caused by invalid input types. Fix these errors (fields marked with a red background) before saving.", new ConfirmationCallback(){

					@Override
					public void onResult(boolean result) {
						widget.setFocus(true);
					}
					
				});
				widget.setFocus(true);
				return true;
			}
		}
		
		return false;
	}
	
	
}
